package c_api

import (
	"gintest/models"
	"gintest/until"
	"github.com/gin-gonic/gin"
	"regexp"
	"strconv"
	"net/http"
	"io/ioutil"
	"encoding/json"
	"time"
)

//接收数据
type Request struct{
	Phone string `json:"phone"` //手机号
	Code string `json:"code"`  //验证码
	PassWord string `json:"password"`//密码
}
/***
	登陆账号
	param phone 手机号
	      code 验证码
	return token 登陆凭证
*/
func External_login(c *gin.Context){
	var data Request
	if err:=c.ShouldBindJSON(&data) ;err!=nil {
		until.Fail(c,1,err.Error())
		return
	}
	//手机号验证
	reg := `^1([38][0-9]|14[579]|5[^4]|16[6]|7[1-35-8]|9[189])\d{8}$`
	rgx := regexp.MustCompile(reg)
	if !rgx.MatchString(data.Phone){
		until.Fail(c,1,"手机号码错误")
		return
	}
	
	//验证码位数验证
	if len(data.Code)!=6{
		until.Fail(c,1,"验证码错误")
		return
	}
	//验证码存在验证
	if err:=models.CheckCode(data.Code,data.Phone);err!=nil{
		until.Fail(c,1,err.Error())
		return
	}
	user:=models.GetUserByPhone(data.Phone)
	if user.Id<=0{
		until.Fail(c,1,"用户未注册")
		return
	}
	//添加注册后自动登陆
	token:=until.Token{
		Id:user.Id,
		UserName:user.UserName,
		Phone:user.Phone,
		PassWord:user.PassWord,
		CreateAt:user.CreateAt,
		UpdateAt:user.UpdateAt,
		Status:0,
	}
	token_key:=until.PutToken(token,"api_")

	until.Success(c,gin.H{"token":token_key})
}
/***
	注册账号
	param phone 手机号
	      code 验证码
	return token 登陆凭证
*/
func External_register(c *gin.Context){
	var data Request
	if err:=c.ShouldBindJSON(&data) ;err!=nil {
		until.Fail(c,1,err.Error())
		return
	}
	//手机号验证
	reg := `^1([38][0-9]|14[579]|5[^4]|16[6]|7[1-35-8]|9[189])\d{8}$`
	rgx := regexp.MustCompile(reg)
	if !rgx.MatchString(data.Phone){
		until.Fail(c,1,"手机号码错误")
		return
	}
	//手机号唯一验证
	if models.UniqueUserPhone(0,data.Phone)>0{
		until.Fail(c,1,"手机号码已注册")
		return
	}
	//验证码位数验证
	if len(data.Code)!=6{
		until.Fail(c,1,"验证码错误")
		return
	}
	//验证码存在验证
	if err:=models.CheckCode(data.Code,data.Phone);err!=nil{
		until.Fail(c,1,err.Error())
		return
	}
	user:=models.User{
		UserName:"un_"+data.Phone,
		Phone:data.Phone,
		NickName:"nn_"+data.Phone,
	}
	if err:=models.AddUser(&user);err!=nil{
		until.Fail(c,1,err.Error())
		return
	}
	//添加注册后自动登陆
	token:=until.Token{
		Id:user.Id,
		UserName:user.UserName,
		Phone:user.Phone,
		PassWord:user.PassWord,
		CreateAt:user.CreateAt,
		UpdateAt:user.UpdateAt,
		Status:0,
	}
	token_key:=until.PutToken(token,"api_")

	until.Success(c,gin.H{"token":token_key})
}
/***
	获取手机验证码
	param phone 手机号
	return json 
*/
func External_getcode(c *gin.Context){
	var data Request
	if err:=c.ShouldBindJSON(&data) ;err!=nil {
		until.Fail(c,1,err.Error())
		return
	}
	//手机号验证
	reg := `^1([38][0-9]|14[579]|5[^4]|16[6]|7[1-35-8]|9[189])\d{8}$`
	rgx := regexp.MustCompile(reg)
	if !rgx.MatchString(data.Phone){
		until.Fail(c,1,"手机号码错误")
		return
	}
	//生成验证码
	code:=""
	for i:=0;i<6;i++{
		code=code+strconv.FormatInt(until.RangeRand(1,9),10)
	}
	if err:=models.AddPhoneCode(code,data.Phone);err!=nil{
		until.Fail(c,1,"错误")
		return
	}
	until.Success(c, gin.H{"code":code})
}

type bcdata struct{
	Openid string    `json:"openid"`
	SessionKey string `json:"session_key"`
	Unionid string `json:"unionid"`
	Errcode int `json:"errcode"`
	Errmsg string `json:"errmsg"`
}
func External_login_xcx(c *gin.Context){
	var data Request
	if err:=c.ShouldBindJSON(&data) ;err!=nil {
		until.Fail(c,1,err.Error())
		return
	}
	if data.Code==""{
		until.Fail(c,1,"code不能空")
		return
	}
	resp, err := http.Get("https://api.weixin.qq.com/sns/jscode2session?appid=wx24084cd55b2b0d3b&secret=592db6a10b050d8222750ac2b6b0e5c8&js_code="+data.Code+"&grant_type=authorization_code")
    if err != nil {
        until.Fail(c,1,"错误")
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if resp.StatusCode != 200 {
        until.Fail(c,2,"错误")
		return
	}
	var bc bcdata
	err=json.Unmarshal(body,&bc)
	if bc.Errcode !=0{
		until.Fail(c,2,bc.Errmsg)
		return
	}
	var key string
	if bc.Unionid!=""{
		key=bc.Unionid
	}else{
		key=bc.Openid
	}
	var user models.User
	user=models.GetUserByOpenId(key)
	if user.Id<=0{
		user=models.User{
			UserName:"un_"+key,
			Phone:key,
			NickName:"nn_"+key,
		}
		user.UserThird=append(user.UserThird,models.UserThird{ThirdKey:key,ThirdType:1,CreateAt:time.Now(),UpdateAt:time.Now()})
		err:=models.AddUser(&user)
		if err!=nil{
			until.Fail(c,1,"错误")
			return
		}
	}
	//添加注册后自动登陆
	token:=until.Token{
		Id:user.Id,
		UserName:user.UserName,
		Phone:user.Phone,
		PassWord:user.PassWord,
		CreateAt:user.CreateAt,
		UpdateAt:user.UpdateAt,
		Status:0,
	}
	token_key:=until.PutToken(token,"api_")

	until.Success(c,gin.H{"token":token_key})
}